<template>
  <div>
    <div v-if="learning===false">
      <div v-if="isEnterCollect===false">
        <el-input class="firstLine" v-model="searchKeyword" placeholder="请输入要查询的合集"  style="width: 200px" size="mini" clearable ></el-input>
        <el-button class="firstLine" size="mini" type="primary"  @click="searchCollect">查询</el-button>
        <el-button class="firstLine" size="mini" type="success"  @click="addCollectModal=true">新增</el-button>

        <el-table :data="collectsData" stripe  border :height="680">
          <el-table-column
              prop="name" :show-overflow-tooltip="true"
              label="名称"
              width="280">
          </el-table-column>
          <el-table-column :show-overflow-tooltip="true"
                           prop="source"
                           label="来源"
                           width="50">
          </el-table-column>
          <el-table-column :show-overflow-tooltip="true"
                           prop="sourceInfo"
                           label="来源说明"
                           width="350">
          </el-table-column>
          <el-table-column
              prop="gameNum"
              label="对局数"
              width="80">
          </el-table-column>
          <el-table-column
              prop="createAt"
              label="更新时间"
              width="180">
          </el-table-column>
          <el-table-column
              fixed="right"
              label="操作"
          >
            <template slot-scope="scope">
              <el-button type="primary" size="mini" @click="selectCollect(scope.row)">选择</el-button>
              <el-button type="warning" size="mini" @click="editCollect(scope.row)">编辑</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div v-if="isEnterCollect===true">
        <Game :collect-name="selectCollectName" :hash-name="selectHashName"></Game>
      </div>

    </div>

    <div v-if="learning===true">
<!--      学习模式-->
    </div>
<!--    dialog-->
    <div>
      <el-dialog
          :visible.sync="addCollectModal"
          title="编辑合集"
          width="800px"
          :close-on-click-modal="false"
          :close-on-press-escape="false"
      >
        <el-form :model="createCollectForm" label-width="80px" :rules="collectRules" ref="createCollectForm">
          <el-form-item label="合集名称" prop="name">
            <el-input v-model="createCollectForm.name"></el-input>
          </el-form-item>
          <el-form-item label="来源" prop="source">
            <el-select v-model="createCollectForm.source" placeholder="请选择">
              <el-option label="书籍" value="书籍"></el-option>
              <el-option label="网络" value="网络"></el-option>
              <el-option label="棋手" value="棋手"></el-option>
              <el-option label="其他" value="其他"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="来源信息" prop="sourceInfo">
            <el-input v-model="createCollectForm.sourceInfo" type="textarea"  :rows="4"></el-input>
          </el-form-item>
        </el-form>

        <el-button @click="addCollectModal = false;isEditCollect = false" size="mini">取消</el-button>
        <el-button type="primary" @click="addCollect" size="mini">确定</el-button>
      </el-dialog>
    </div>
  </div>
</template>

<script>

import Database from "@/lib/database";
import {arr2HashMap, invoke} from "@/lib/utils";
import Sqlite from "@/lib/sqlite";
import Chessmate from "@/lib/chessmate";
import path from "path";
import emitvue from "@/lib/emitvue";
import Game from "@/components/collect/Game.vue";
import * as utils from "@/lib/utils";
import _ from "lodash";

export default {
  name: "Collect",
  data() {
    return {
      isDev: false,
      learning: false,


      // 编辑合集相关逻辑
      searchKeyword: '',
      addCollectModal: false,
      // 筛选出的当前合集
      collectsData: [],
      createCollectForm: {
        name: '',
        description: '',
        source: '',
        sourceInfo: ''
      },
      collectRules: {
        name: [
            { required: true, message: '请输入名称', trigger: 'blur' }
        ],
        source: [
          { required: true, message: '请选择来源', trigger: 'blur' }
        ],
        sourceInfo: [
          { required: true, message: '请输入来源信息', trigger: 'blur' }
        ],
      },
      isEditCollect: false,
      oldCollectName: '', // 旧合集名称

      // 合集内棋局模块
      isEnterCollect: false,
      selectCollectName: '',
      selectHashName: ''
    }
  },
  methods: {
    // 获取设置
    async getSetting() {
      this.appPath = await invoke('getCurrentPath', null)
      let config = await invoke('get', {name: 'setting', type: 'database'})

      if (!config) {
        await invoke('set', JSON.stringify({name: 'setting', type: 'database', dbPath: '', enginePath: ''}))
      } else {
        if (!config.gamePath) {
          config.gamePath = path.join(config.dbFolderPath, './game.db')
          await invoke('set', JSON.stringify({name: 'setting', type: 'database', ...config}))
        }
        await Sqlite.connectGame(config.gamePath)
        // 需要连接教程库来获取数据
        await Sqlite.connectTutorial(config.tutorialDbPath)
        const chessConfig = {
          path: config.enginePath,
          analyzeSpeed: config.analyzeSpeed,
          blunderThreshold: config.blunderThreshold,
          mistakeThreshold: config.mistakeThreshold,
        }
        this.exportFilePath = config.exportFilePath || './'
        await Chessmate.init(chessConfig)
      }
    },
    //从数据库查询合集
    async searchCollect() {
      this.collectsData = await Database.getGameCollect(this.searchKeyword)
      if (this.collectsData.length) {
        const gameInfo = await Database.countGameInCollect()
        const gameCountMap = utils.arr2HashMap(gameInfo, 'hashName')
        const temp = this.collectsData
        for (const item of temp) {
          item.gameNum = gameCountMap[item.hashName]?.count || 0
        }
        // 防止双向绑定不刷新页面
        this.collectsData = _.cloneDeep(temp)
      }
    },

    // 新增合集
    async addCollect() {
      const res = await this.$refs['createCollectForm'].validate();
      if (!res) return
      console.log("this.createCollectForm", this.createCollectForm)
      if (this.isEditCollect) {
        console.log("edit")
        await Database.editGameCollect(this.oldCollectName, this.createCollectForm)
        this.addCollectModal = false
        this.isEditCollect = false
        await this.searchCollect()
        return this.$notify({duration: 1000, title: '通知', message: "编辑成功", type: 'success'})
      }
      const addRes = await Database.saveGameCollect(this.createCollectForm)
      if (!addRes) return this.$notify({duration: 1000, title: '通知', message: "名称与现有合集重复，请修改", type: 'warning'})
      this.addCollectModal = false
      await this.searchCollect()
      return this.$notify({duration: 1000, title: '通知', message: "编辑成功", type: 'success'})
    },
    async editCollect(data) {
      console.log("data", data)
      this.oldCollectName = data.name
      this.createCollectForm = data
      this.addCollectModal = true
      this.isEditCollect = true
    },
    async selectCollect(data) {
      this.isEnterCollect = true
      this.selectCollectName = data.name
      this.selectHashName = data.hashName

    },
  },
  async mounted() {
    if (location.protocol.indexOf('http') !== -1) {
      this.isDev = true
    }

    await this.getSetting()
    await this.searchCollect()
    emitvue.$on('backCollect', ()=> {
      this.isEnterCollect = false
    })
    emitvue.$on('refreshSetting', async () => {
      await this.getSetting()
    })
  },
  components: {
    Game
  },
}
</script>


<style scoped>
.firstLine {
  display: inline-block;
  margin: 5px;
}

</style>